package authmiddleware

import (
	"Yoj/internal/dao"
	"fmt"
	"github.com/gogf/gf/v2/errors/gcode"
	"github.com/gogf/gf/v2/errors/gerror"
	"github.com/gogf/gf/v2/net/ghttp"
	"github.com/gogf/gf/v2/os/glog"
	"github.com/golang-jwt/jwt/v5"
)

type Role struct {
	Role string `orm:"Role"`
}

func GetRole(qid string, r *ghttp.Request) (string, error) {
	ctx := r.GetCtx()

	role := Role{}
	err := dao.User.Ctx(ctx).Where("Qid = ?", qid).Fields(dao.User.Columns().Role).Scan(&role)
	if err != nil {
		glog.Error(ctx, err)
		return "", gerror.NewCode(gcode.CodeInternalError, "查询数据出错")
	}
	return role.Role, nil
}

func AdminAuther(r *ghttp.Request) {
	glog.Print(r.GetCtx(), fmt.Sprintf("Token: %s", r.Header.Get("Authorization")))

	tokenString := r.Header.Get("Authorization")
	if tokenString == "" {
		r.SetError(gerror.NewCode(gcode.CodeNotAuthorized, "未提供Token"))
		return
	}

	if len(tokenString) > 7 && tokenString[:7] == "Bearer " {
		tokenString = tokenString[7:]
	}

	claims := &JWTClaims{}
	_, err := jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (interface{}, error) {
		return []byte(JWTsecret), nil
	})
	if err != nil {
		r.SetError(gerror.NewCode(gcode.CodeNotAuthorized, "Token无效"))
		return
	}

	glog.SetLevel(glog.LEVEL_DEBU)

	role, err := GetRole(claims.Qid, r)
	if err != nil {
		r.SetError(gerror.NewCode(gcode.CodeInternalError, "查询数据出错"))
		return
	}
	// TODO: 从数据库来判断权限;
	if role != "Tester" && role != "Admin" {
		r.SetError(gerror.NewCode(gcode.CodeNotAuthorized, "无权限"))
		return
	}

	r.Middleware.Next()
}
